﻿using Nop.Core.Domain.Logistics;
using System.Collections.Generic;
using System.Linq;

namespace Logistics.Services.Strategy
{
    public class FixGoWaypointsStrategy : StrategyBase
    {
        public override void Caculate()
        {
            foreach (var da in Plan.DriverAssignments)
            {
                PlanSingleDriver(da);
            }
        }

        public override int Priorty
        {
            get { return 30; }
        }

        private void PlanSingleDriver(DriverAssignment da)
        {
            if (da.GoWaypoints != null)
            {
                var gwps = new List<LogisticsLocation>(da.GoWaypoints);
                var rwps = RemoveWrongWaypoints(gwps);
                da.GoWaypoints = gwps.ToArray();
                da.ReturningWaypoints = rwps.ToArray();
            }
        }

        private List<LogisticsLocation> RemoveWrongWaypoints(List<LogisticsLocation> wps)
        {
            var drops = wps.Where(wp => wp.Status == LocationStatus.PendingDropOff);
            var removed = new List<LogisticsLocation>();
            foreach (var d in drops)
            {
                // TODO: Check the relatedLocation status
                if (d.RelatedLocation != null && d.Rank < d.RelatedLocation.Rank)
                {
                    wps.Remove(d);
                    removed.Add(d);
                }
            }
            return removed;
        }
    }
}